package cn.quevo.spring.util;

import cn.quevo.core.enums.FileTypeEnum;
import cn.quevo.core.file.FileUtils;
import cn.quevo.core.file.Images;
import cn.quevo.core.file.ImagesUtil;
import cn.quevo.core.lang.StringUtils;
import cn.quevo.spring.entity.Upload;
import cn.quevo.spring.entity.UploadResult;
import cn.quevo.spring.enums.UploadStatusEnum;
import cn.quevo.spring.exception.UploadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Map;

public class FileUploadUtils {
    private final static Logger log = LoggerFactory.getLogger(FileUploadUtils.class);

    /**
     * 文件上传
     *
     * @param upload
     */
    public static void upload(Upload upload) {
        upload(upload, WebUtils.getHttpServletRequest());
    }

    /**
     * 文件上传
     *
     * @param upload
     * @param request
     * @return
     */
    public static UploadResult upload(Upload upload, HttpServletRequest request) {
        // 验证是否文件上传
        if (!(request instanceof MultipartHttpServletRequest)) {
            throw new UploadException(UploadStatusEnum.FILE_EMPTY);
        }
        // 将request变成多部分request
        Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
        if (StringUtils.isEmpty(fileMap)) {
            throw new UploadException(UploadStatusEnum.FILE_EMPTY);
        }
        String fileName = "";
        for (Map.Entry<String, MultipartFile> mfile : fileMap.entrySet()) {
            if (mfile == null) {
                continue;
            }
            return upload(upload, mfile).setRequestParams(WebUtils.getParameterMap(request,""));
        }
        throw new UploadException(UploadStatusEnum.FILE_EMPTY);
    }

    /**
     * 文件上传
     *
     * @param upload
     * @param mfile
     * @return
     */
    public static UploadResult upload(Upload upload, Map.Entry<String, MultipartFile> mfile) {
        UploadResult uploadResult = new UploadResult();
        String diskPath = Paths.get(upload.getDiskPath()).normalize().toString();
        try {
            String suffix = FileUtils.getFileSuffix(mfile.getValue().getOriginalFilename());
            String exts = StringUtils.isBlank(upload.getExts()) ? upload.getFileTypeEnum().getValue() : upload.getExts();
            if (!"*".equalsIgnoreCase(exts)) {
                if (!StringUtils.contains(suffix, exts.split(","))) {
                    throw new UploadException(UploadStatusEnum.FILE_TYPE_FAILD.getCode(), UploadStatusEnum.FILE_TYPE_FAILD.getValue().concat(",仅支持：").concat(exts));
                }
                // 判断是否图片
                if (StringUtils.contains(suffix, FileTypeEnum.IMG.getValue().split(","))) {
                    Images images = ImagesUtil.getImagesByInputStream(mfile.getValue().getInputStream());
                    uploadResult.setImgHeight(images.getHeight());
                    uploadResult.setImgWidth(images.getHeight());
                }
            }
            if (upload.getMaxSize() != null && !StringUtils.isBlank(upload.getMaxSize(), 1)) {
                if (mfile.getValue().getSize() > upload.getMaxSize().longValue()) {
                    throw new UploadException(UploadStatusEnum.FILE_ILLEGAL);
                }
            }
            String fileName = FileUtils.getFileNameCurTime(mfile.getValue().getOriginalFilename());
            FileUtils.copyLocation(mfile.getValue().getInputStream(),fileName, diskPath, upload.getCopyPath());
            uploadResult.setFileName(fileName);
            uploadResult.setFileSize(mfile.getValue().getSize());
            uploadResult.setRelativePath(upload.getSavePath());
            uploadResult.setFulleName(Paths.get(upload.getSavePath()).resolve(fileName).normalize().toString());
            return uploadResult;
        } catch (IOException e) {
            throw new UploadException(UploadStatusEnum.NO_PERMISSIONS, e);
        }
    }
}
